var prefix = "/approval";
var attachment = new Map();
var initFormData = new FormData();
var initApproverCount = '';
$(function() {
    $(window).bind('beforeunload', function(){
        return '您可能有数据没有保存';
    });

    $(document).on('change','#upFile', function(e){
        processFiles(this.files);
        event.target.value='';
    })

	$("#submitBtn").bind("click",submitEvent);
    $("#cancelBtn").bind("click",cancelEvent);

	load();

    $("#userInput").autocomplete({
        minLength: 2,
        delay:1000,

        source: function( request, response ) {
            if($("#userInput").val().trim().indexOf('%')===0){
                $.ajax({
                    method:'get',
                    url: prefix+"/line/listLine/"+$("#userInput").val().trim().replace('%',''),
                    dataType: "json",
                    success: function(data) {
                        response( $.map(data,function(item) {
                            return {
                                label: item.lineName,
                                value: item.lineId,
                                empMail:'saved line'
                            }
                        }));
                    }
                });
            }else {
                $.ajax({
                    method: 'post',
                    url: "/employee/empSearch/findByFullName",
                    dataType: "json",
                    data: {
                        fullName: $("#userInput").val().trim().toLowerCase()
                    },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.empNm + '  ' + item.empJob,
                                value: item.empMail,
                                empId: item.empId,
                                empNm: item.empNm,
                                empDept: item.empDept,
                                empJob: item.empJob,
                                empManager: item.empManager,
                                empMail: item.empMail
                            }
                        }));
                    }
                });
            }
        },

        create: function() {
            $(this).data('ui-autocomplete')._renderItem = function (ul,item){
                return $( "<li>" )
                    .append( "<dl  class='searchedUerList'  >"+
                        "<dt>"+
                        "<span>"+item.label+"</span>"+
                        "</dt>"+
                        "<dd>"+
                        "<img class='searchedUerIcon' src='/img/approval/user_icon.jpg' >"+
                        "</dd>"+
                        "<dd>"
                        +item.empMail+
                        "</dd>"+
                        "</dl> ")
                    .appendTo( ul );
            };
        },

        _renderMenu: function( ul, items ) {
            var that = this;
            $.each( items, function( index, item ) {
                that._renderItemData( ul, item );
            });
            $( ul ).find( "li:odd" ).addClass( "odd" );
        },

        _resizeMenu: function() {
            this.menu.element.outerWidth( 500 );
        },

        select: function ( event, ui ) {
            if(ui.item.empMail !== 'saved line'){
                var exist = false;
                $('#userList li').each(function () {
                    if ($(this).find("[id='seq']").data('mail') == ui.item.empMail) {
                        layer.alert(''+ui.item.empNm +'&nbsp;'+ ui.item.empMail +'<br>Duplicate user found. Please delete the duplicate user.',
                            {
                                title: 'Notification',
                                btn: ['Ok']
                            }
                        );
                        exist = true;
                        return false;
                    }
                });
                if (exist == false) {
                    var seq_last = parseInt($("#userList li:last-child ").index());
                    $("#userList").append(
                        "<li class='singleApp'>" +
                        "<span id='seq' data-mail='" + ui.item.empMail + "'>" + (seq_last + 1) + "</span>" +
                        "<button id='appBtn' class='type_button active' title='Approval' value ='1' >Appr</button>" +
                        "<button id='conBtn' class='type_button' title='Consent' value ='2'>Cons</button>" +
                        "<button id='notiBtn' class='type_button' title='Notification' value ='9'>Noti</button>" +
                        "<span id='postAppr' class='post_appr'  value ='3' style='display:none'>Post approval</span>" +
                        "<span id='paraAppr' class='para_appr'  value ='7' style='display:none'>Parallel approval</span>" +
                        "<span id='paraCon' class='para_con'  value ='4' style='display:none'>Parallel consent</span>" +
                        "<p>" + ui.item.empNm + '/' + ui.item.empJob + "</p>" +
                        "<input type='hidden' id='empId' value='" + ui.item.empId + "'/>" +
                        "<span id='operation' class='appOperation'><i class='fa fa-times'></i></span>" +
                        "<span id='arbDecision' class='appOperation' title='Arbitrary decision'><i class='fa fa-gavel'></i></span>" +
                        "<span id='editText' class='appOperation'title='Edit text'><i class='fa fa-pencil'></i></span>" +
                        "<span id='changeLine' class='appOperation' title='Change line'><i class='fa fa-user'></i></span>" +
                        "<input type='hidden' id='preReadTime' />" +
                        "<input type='hidden' id='receiptTime' />" +
                        "<input type='hidden' id='readTime' />" +
                        "<input type='hidden' id='handleTime' />" +
                        "<input type='hidden' id='changeLineYn' />" +
                        "<input type='hidden' id='changeTextYn' />" +
                        "<input type='hidden' id='remark' />" +
                        "</li>"
                    );
                    wrapper.totalLines ++;
                    $(".save_line_body").height($(".save_line_body").height() + $("#userList li:last-child").outerHeight(true));

                    reorder();//公共排序方法
                }
            }else{
                $.ajax({
                    url : prefix + "/lineDetail/listLineDetail/"+ui.item.value,
                    type : "get",
                    success : function(r) {
                        if(r.list !== undefined){
                            var lineLength =r.list.length;
                            $.each(r.list, function(index,lineDetail) {
                                var exist = false;
                                $('#userList li').each(function () {
                                    if ($(this).find("[id='seq']").data('mail') == lineDetail.mail) {
                                        exist = true;
                                        lineLength--;
                                        return false;
                                    }
                                });
                                if (exist == false) {
                                    $("#userList").append(
                                        "<li class='singleApp'>" +
                                        "<span id='seq' data-mail='" + lineDetail.mail + "'></span>" +
                                        "<button id='appBtn' class='type_button activeHide' title='Approval' value ='1' >Appr</button>" +
                                        "<button id='conBtn' class='type_button' title='Consent' value ='2'>Cons</button>" +
                                        "<button id='notiBtn' class='type_button' title='Notification' value ='9'>Noti</button>" +
                                        "<span id='postAppr' class='post_appr'  value ='3' style='display:none'>Post approval</span>" +
                                        "<span id='paraAppr' class='para_appr'  value ='7' style='display:none'>Parallel approval</span>" +
                                        "<span id='paraCon' class='para_con'  value ='4' style='display:none'>Parallel consent</span>" +
                                        "<p>" + lineDetail.name+ '/' + lineDetail.job + "</p>" +
                                        "<input type='hidden' id='empId' value='" + lineDetail.receiverEpid + "'/>" +
                                        "<span id='operation' class='appOperation'><i class='fa fa-times'></i></span>" +
                                        "<span id='arbDecision' class='appOperation' title='Arbitrary decision'><i class='fa fa-gavel'></i></span>" +
                                        "<span id='editText' class='appOperation'title='Edit text'><i class='fa fa-pencil'></i></span>" +
                                        "<span id='changeLine' class='appOperation' title='Change line'><i class='fa fa-user'></i></span>" +
                                        "</li>"
                                    );
                                    switch (parseInt(lineDetail.type)) {
                                        // case 0:
                                        //     $('#userList li').find('.type_button').remove();
                                        //     $("#userList li:last-child #seq").after("<button id='draftBtn' class='draftBtn active' value ='0'>Draft</button>");
                                        //     $("#userList li:last-child .appOperation").remove();
                                        //     break;
                                        case 1:
                                            $("#userList li:last-child button:nth-of-type(1)").addClass('active');
                                            break;
                                        case 2:
                                            $('#userList li:last-child #appBtn').removeClass('activeHide');
                                            $("#userList li:last-child button:nth-of-type(2)").addClass('active');
                                            break;
                                        case 9:
                                            $('#userList li:last-child #appBtn').removeClass('activeHide');
                                            $("#userList li:last-child button:nth-of-type(3)").addClass('active');
                                            break;
                                        case 3:
                                            $('#userList li:last-child .type_button').removeClass('activeHide').hide();
                                            $("#userList li:last-child #postAppr").addClass('active').show();
                                            break;
                                        case 7:
                                            $('#userList li:last-child .type_button').hide();
                                            $("#userList li:last-child #paraAppr").addClass('active').show();
                                            break;
                                        case 4:
                                            $('#userList li:last-child .type_button').hide();
                                            $("#userList li:last-child #paraCon").addClass('active').show();
                                            break;
                                    };

                                    if(lineDetail.arbPmtYn == 'N'){
                                        $("#userList li:last-child #arbDecision").addClass('clicked');
                                    }
                                    if(lineDetail.txtMdfyPmtYn == 'N'){
                                        $("#userList li:last-child #editText").addClass('clicked');
                                    }
                                    if(lineDetail.pathMdfyPmtYn == 'N'){
                                        $("#userList li:last-child #changeLine").addClass('clicked');
                                    }
                                }
                            });

                            $(".save_line_body").height($(".save_line_body").height()+$("#userList li:last-child").outerHeight(true)*(lineLength));
                            wrapper.totalLines = $("#userList li").length-1;
                        }
                        reorder();
                    },
                    error: function(){
                        layer.msg("Server error")
                    }
                });
            }

        },

        open: function() {
            $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },

        close: function() {
            $("#userInput").val('');
        },

        classes: {
            "ui-autocomplete": "highlight"
        },

    });

    //选定当前审批人
    $('#userList').on('click','li',function(){
        if($(this).attr('class') == 'singleApp block'){
            return;
        }
        if(event.ctrlKey){
            if ($(this).attr('class')=='singleApp picked'){
                $(this).removeClass('picked');
            }
            else{
                $(this).addClass('picked');
            }
        }
        else{
            //将选中的class设置为.singleApp.picked，其余为原来
            $(this).addClass('picked').siblings().removeClass('picked');
        }
        $("#userList li:first-child").removeClass('picked')
    });

    //改变当前审批人角色
    $("#userList").on('click', '.type_button', function(){
        var title = $(this).attr('title');
        switch (title) {
            case 'Approval':
                $(this).addClass('active').siblings('button').attr('class','type_button');
                $(this).parent().find('.appOperation').removeClass('clicked').show();
                break;
            case 'Consent':
                $(this).addClass('active').siblings('button').attr('class','type_button');
                $(this).parent().find("[id='arbDecision']").addClass('clicked').show();
                $(this).parent().find("[id='editText']").removeClass('clicked').show();
                $(this).parent().find("[id='changeLine']").removeClass('clicked').show();
                break;
            case 'Notification':
                $(this).addClass('active').siblings('button').attr('class','type_button');
                $(this).parent().find('.appOperation').not('#operation').addClass('clicked').hide();
                break;
        }

        reorder();
    });

    //批量改变选中的审批人角色
    $("#RoleChangeBtn").on('click', '.icon_button', function(){
        cancelPara();

        $('#userList .picked').find('.post_appr').removeClass('active').hide();
        $('#userList .picked').find('.para_appr').removeClass('active').hide();
        $('#userList .picked').find('.para_con').removeClass('active').hide();
        $('#userList .picked').find('.type_button').show();

        var roleTitle = $(this).attr('title');
        switch (roleTitle) {
            case 'Approval':
                $('#userList .picked').find("[id='appBtn']").addClass('active').siblings('button').attr('class','type_button');
                $('#userList .picked').find('.appOperation').removeClass('clicked').show();
                break;
            case 'Consent':
                $('#userList .picked').find("[id='conBtn']").addClass('active').siblings('button').attr('class','type_button');
                $('#userList .picked').find("[id='arbDecision']").addClass('clicked').show();
                $('#userList .picked').find("[id='editText']").removeClass('clicked').show();
                $('#userList .picked').find("[id='changeLine']").removeClass('clicked').show();
                break;
            case 'Notification':
                $('#userList .picked').find("[id='notiBtn']").addClass('active').siblings('button').attr('class','type_button');
                $('#userList .picked').find('.appOperation').not('#operation').addClass('clicked').hide();
                break;
        }

        reorder();
    });

    //后批角色
    $("#PostRoleBtn").on('click',function () {
        cancelPara();

        $('#userList .picked').find('.type_button').removeClass('activeHide').removeClass('active').hide();
        $('#userList .picked').find('.para_appr').removeClass('active').hide();
        $('#userList .picked').find('.para_con').removeClass('active').hide();
        $('#userList .picked').find('.post_appr').addClass('active').show();
        $('#userList .picked').find('.appOperation').not('#operation').addClass('clicked').hide();

        reorder();
    });

    //平行角色
    $("#ParRoleBtn").on('click',function () {
        var count= $('#userList .picked').size();
        if (count < 2){
            layer.alert('Please select 2 or more parallel approvers.');
            return;
        }else{
            $('#userList').find('.activeHide').addClass('active');//取消平行时，根据为activeHide的，转化为原来的active。
            $('#userList').find('.type_button.active').show().siblings('button').show();
            $('#userList').find('.para_appr').removeClass('active').hide();
            $('#userList').find('.para_con').removeClass('active').hide();
        }

        $('#userList .picked').each(function () {
            var $Role =$(this).find('.active').attr('title');
            if($Role != 'Approval' && $Role != 'Consent' )
            {
                layer.msg('Parallel can be specified only by the approver or consenter.');
                cancelPara();
                return false;
            }

            var $Role =$(this).find('.active').attr('title');
            if($Role == 'Approval'){
                $(this).find('.type_button').removeClass('active').hide();
                $(this).find("[id='appBtn']").addClass('activeHide');  //将其激活状态隐藏，取消平行时根据哪个为hide再重新激活至原先的角色
                $(this).find('.para_appr').addClass('active').show();
                $(this).find('.appOperation').removeClass('clicked');
            }
            else if($Role == 'Consent'){
                $(this).find('.type_button').removeClass('active').hide();
                $(this).find("[id='conBtn']").addClass('activeHide');
                $(this).find('.para_con').addClass('active').show();
                $(this).find("[id='arbDecision']").addClass('clicked');
                $(this).find("[id='editText']").removeClass('clicked');
                $(this).find("[id='changeLine']").removeClass('clicked');
            }
        });

        reorder();
    });

    //取消平行
    $("#CancelParBtn").on('click',function () {
        cancelPara();
        reorder();
    });

    //审批人上移
    $("#top_arrow").on("click",function () {
        $('#userList .picked').each(function () {
            var index = $(this);
            if($(this).prevAll().length>1){
                var preParentClass = index.prev().find('.active').parent().attr('class');
                if(preParentClass == 'singleApp block'){
                    return false;
                }else{
                    var preClass = index.prev().find('.active').attr('class');
                    if(preClass == 'para_appr active' || preClass == 'para_con active') {//上面的第一个元素是平行
                        var indexClass = index.find('.active').attr('class')
                        if (indexClass == 'para_appr active' || indexClass == 'para_con active' ){//点击的也是平行，即平行之间互换
                            index.prev().before(index);
                        }else{//上面的第一个元素是平行，点击的是非平行
                            var paraAppCount= $('#userList').find('.para_appr.active').size();
                            var paraConCount= $('#userList').find('.para_con.active').size();
                            var totalPara = paraAppCount + paraConCount;
                            index.prevAll().eq(totalPara-1).before(index);
                        }
                    }else{
                        index.prev().before(index);
                    }
                }
            }
        });
        reorder();
    });

    //审批人下移
    $("#bottom_arrow").on("click",function () {
        $('#userList .picked').each(function () {
            var index = $(this);
            if($(this).prevAll().length > 0 && $(this).nextAll().length > 0){
                var indexClass = index.find('.active').attr('class')
                var nextClass = index.next().find('.active').attr('class');
                if(nextClass == 'para_appr active' || nextClass == 'para_con active' ){
                    if(indexClass == 'para_appr active' || indexClass == 'para_con active'){
                        index.next().after(index);
                    }else{
                        index.nextAll().find('.para_con.active,.para_appr.active').parent('li').first().after(index);
                    }
                }else{
                    if(indexClass == 'para_appr active' || indexClass == 'para_con active'){
                        index.prevAll().find('.para_appr.active,.para_con.active').parent('li').first().before(index.next());
                    }else{
                        index.next().after(index);
                    }
                }
            }
        });
        reorder();
    });

    //单个审批人删除
    $("#userList").on('click', '#operation', function(){
        var clickApp = $(this).parent('li').find('#empId').attr('value');
        if(clickApp == JSON.parse(sessionStorage.getItem("howAreYou")).userId)
        {
            layer.msg('You can\'t delete yourself');
            return;
        }

        $(".save_line_body").height($(".save_line_body").height() - $("#userList li:last-child").outerHeight(true));
        $(this).parent('li').remove();
        wrapper.totalLines --;
        cancelPara()
        reorder();
    });

    //多个审批人删除
    $("#deleteApp").on('click', function(){
        //不能删除自己
        var pickedSelf;
        $('#userList .picked').each(function () {
            var clickApp = $(this).find('#empId').attr('value');

            if(clickApp == JSON.parse(sessionStorage.getItem("howAreYou")).userId)
            {
                layer.msg('You can\'t delete yourself');
                pickedSelf = true;
                return false;
            }
        });
        if(pickedSelf) return;
        //end


        var deleteHeight = 0;
        $('#userList .picked').each(function () {
            deleteHeight = deleteHeight+ $(this).outerHeight(true);
            wrapper.totalLines --;
        })
        $(".save_line_body").height($(".save_line_body").height() - deleteHeight);
        $('#userList .picked').remove();
        cancelPara();
        reorder();
    });

    //单个审批人权限设置
    $("#userList").on('click', '.appOperation', function(){
        if($(this).attr('class')=='appOperation clicked'){
            $(this).removeClass('clicked');
        }else{
            $(this).addClass('clicked');
        }
    });

    //附件上移
    $("#top_file").on("click",function () {
        $('#fileList li').each(function () {
            var index = $(this).find('.check').is(':checked');
            if(index == true){
                $(this).prev().before($(this));
            }
        });
    });

    //附件下移
    $("#bottom_file").on("click",function () {
        $('#fileList li').each(function () {
            var index = $(this).find('.check').is(':checked');
            if(index == true){
                $(this).next().after($(this));
            }
        });
    });

    //单个附件删除
    $("#fileList").on('click', '#operation', function(){
        if($(this).parent('li').siblings('li').length > 0)
            $(".app_file_body").height($(".app_file_body").height() - $("#fileList li:last-child").outerHeight(true));
        else {
            $(".app_file_body").hide();
            $("#checkAll").prop("checked", false);
        }
        var fileName = $(this).parent('li').find('#fileName').text();
        var fileSize = Number($(this).parent('li').find('#fileSize').data('size'));
        attachment.delete(fileName);
        $(this).parent('li').remove();
        wrapper.totalFiles--;
        wrapper.totalFileSize = Number((wrapper.totalFileSize - fileSize).toFixed(2));
    });

    //多个附件删除
    $("#deleteFile").on("click",function () {
        $("#fileList li").each(function () {
            if ($(this).find('.check').is(':checked')) {
                $(this).remove();
                var fileName = $(this).find('#fileName').text();
                attachment.delete(fileName);
                wrapper.totalFiles--;
                if($("#fileList li").length > 0){
                    $(".app_file_body").height($(".app_file_body").height() - $("#fileList li:last-child").outerHeight(true));
                } else {
                    $(".app_file_body").hide();
                    $("#checkAll").prop("checked", false);
                }
            }
        })

        var sumSize = 0.00;
        $("#fileList li").each(function () {
            sumSize+= Number($(this).find('#fileSize').data('size'));
        })
        wrapper.totalFileSize = Number(sumSize.toFixed(2));
    })

    //附件批量选中
    $(".checkAll").on("click",function () {
        if ($(this).find('#checkAll').is(':checked')){
            $('#fileList li').find('.check').prop("checked",false);
            $("#checkAll").prop("checked",false);
        }else{
            $('#fileList li').find('.check').prop("checked",true);
            $("#checkAll").prop("checked",true);
        }
    })

    //附件单个选中
    $("#fileList").on('click', '.check',function () {
        var checkFile = 0;
        $("#fileList li").each(function () {
                if ($(this).find('.check').is(':checked')) {
                    checkFile++;
                }
            }
        )

        if(checkFile == wrapper.totalFiles){
            $("#checkAll").prop("checked",true);
        }else {
            $("#checkAll").prop("checked",false);
        }
    });

});

var wrapper = new Vue({
    el : '.main_body',
    data : {
        totalLines : 0,
        totalFiles : 0,
        totalFileSize: 0
    }
});

function processFiles(files) {
    var duplicateFiles = new Array();
    var sumSize = 0;
    var amount = files.length;
    for(var i=0; i < files.length; i++) {
        // 取得下一个文件  
        var file = files[i];
        if(isExist(file)){
            duplicateFiles.push(file);
            amount--;
            continue;
        }

        var type = file.type;
        var ico = '';
        if(type.indexOf('image')>-1){
            ico = "<span><i class='fa fa-file-image-o' style='color:#A03638' aria-hidden='true'></i></span>";
        }else if(type.indexOf('compressed')>-1){
            ico = "<span><i class='fa fa-file-archive-o' style='color:#F1B15A' aria-hidden='true'></i></span>";
        }else if(type.indexOf('word')>-1){
            ico = "<span><i class='fa fa-file-word-o' style='color:#2E5790' aria-hidden='true'></i></span>";
        }else if(type.indexOf('excel')>-1){
            ico = "<span><i class='fa fa-file-excel-o' style='color:#1E7145' aria-hidden='true'></i></span>";
        }else if(type.indexOf('sheet')>-1){
            ico = "<span><i class='fa fa-file-excel-o' style='color:#1E7145' aria-hidden='true'></i></span>";
        }else if(type.indexOf('text')>-1){
            ico = "<span><i class='fa fa-file-text-o' style='color:#C0C0C0' aria-hidden='true'></i></span>";
        }else if(type.indexOf('video')>-1){
            ico = "<span><i class='fa fa-file-video-o' style='color:#1E7145' aria-hidden='true'></i></span>";
        }else if(type.indexOf('presentation')>-1){
            ico = "<span><i class='fa fa-file-powerpoint-o' style='color:#8B008B' aria-hidden='true'></i></span>";
        }else if(type.indexOf('pdf')>-1){
            ico = "<span><i class='fa fa-file-pdf-o' style='color:#DC143C' aria-hidden='true'></i></span>";
        }else{
            ico = "<span><i class='fa fa-file' style='color:#0096D6' aria-hidden='true'></i></span>";
        }
        $("#fileList").append(
            "<li>" +
                "<span class='my-checkbox'><input class='check' id='"+file.name+"' type='checkbox' hidden><label for='"+file.name+"'></label></span>" +
                ico +
                "<span id='fileName'>"+file.name+"</span>" +
                "<span id='fileSize' data-size='"+(file.size/(1024*1024)).toFixed(2)+"'>("+(file.size/1024).toFixed(2)+'KB'+")</span>" +
                "<input type='hidden' id='filePath' value='"+file.name+"'/>" +
                "<span id='operation'><i class='fa fa-times'></i></span>" +
            "</li>"
        );
        sumSize+=Number(file.size/(1024*1024));
        attachment.set(file.name,file);
    }

    if($("#fileList li:last-child").outerHeight(true)===0){
        //首次添加
        $(".app_file_body").height($(".app_file_body").height() + 18.4 * (amount-1));
    }else{
        $(".app_file_body").height($(".app_file_body").height() + $("#fileList li:last-child").outerHeight(true) * amount);
    }
    if(duplicateFiles.length>0){
        let str ='';
        //duplicateFiles.forEach(s => {str += '<br>'+s.name});
        $.each(duplicateFiles,function(index, value) {
            str += '<br>'+value.name
        });
        layer.alert("The file has already been attached. "+str);
    }
    wrapper.totalFiles += amount;
    wrapper.totalFileSize = Number((wrapper.totalFileSize + sumSize).toFixed(2));
	$(".app_file_body").show();
}

function isExist(file) {
    let result = false;
    $("#fileList li").each(function () {
        if(file.name === $(this).find('#fileName').text()){
            result = true;
            return false;
        }
    });
    return result;
}

function submitEvent(){
    var formData = new FormData();

    //标题
	var title = $(".set_right_title").val();
	if(!title){
		layer.msg('请填写Title');
		return;
	}
    formData.append('apTtl', title);

    if($("#userList li").length == 1){
        layer.msg('请选择审批人');
        return;
    }

    //附件信息
    // for(let [key, value] of attachment) {
    //     formData.append("files", value);
    // };
    attachment.forEach(function (item) {
         formData.append("files", item);
    });

    //审批人信息
    $.each( $("#userList li"), function(i, li) {
        formData.append('aapTaplnVOList['+i+'].apSeq',$(this).find("[id='seq']").text());
        formData.append('aapTaplnVOList['+i+'].apRlCd',$(this).find(".active").attr("value"));
        formData.append('aapTaplnVOList['+i+'].apRelrEpid',$(this).find("[id='empId']").val());
        formData.append('aapTaplnVOList['+i+'].aprelrmailaddr',$(this).find("[id='seq']").data('mail'));
        formData.append('aapTaplnVOList['+i+'].arbPmtYn',$(this).find("[id='arbDecision']").attr('class')==='appOperation clicked' ? 'N' : 'Y');
        formData.append('aapTaplnVOList['+i+'].txtMdfyPmtYn',$(this).find("[id='editText']").attr('class')==='appOperation clicked' ? 'N' : 'Y');
        formData.append('aapTaplnVOList['+i+'].pathMdfyPmtYn',$(this).find("[id='changeLine']").attr('class')==='appOperation clicked' ? 'N' : 'Y');
        formData.append('aapTaplnVOList['+i+'].preReadTime', $(this).find("[id='preReadTime']").val());
        formData.append('aapTaplnVOList['+i+'].receiptTime', $(this).find("[id='receiptTime']").val());
        formData.append('aapTaplnVOList['+i+'].readTime', $(this).find("[id='readTime']").val());
        formData.append('aapTaplnVOList['+i+'].handleTime', $(this).find("[id='handleTime']").val());
        formData.append('aapTaplnVOList['+i+'].remark', $(this).find("[id='remark']").val() === 'null' ? '' : $(this).find("[id='remark']").val());


        if($(this).find("[id='empId']").val() === JSON.parse(sessionStorage.getItem("howAreYou")).empId){
            if(initApproverCount !== approverCount ) {
                formData.append('aapTaplnVOList['+i+'].changeLineYn', 'Y');
            }
            debugger
            if(initFormData.get('apTtl') !== formData.get('apTtl') || initFormData.get('txtClobcn') !== formData.get('txtClobcn')) {
                formData.append('aapTaplnVOList['+i+'].changeTextYn', 'Y');
            }
        }
        else{
            if($(this).find("[id='changeLineYn']").val() === 'Y'){
                formData.append('aapTaplnVOList['+i+'].changeLineYn', $(this).find("[id='changeLineYn']").val() );
            }
            if($(this).find("[id='changeTextYn']").val() === 'Y'){
                formData.append('aapTaplnVOList['+i+'].changeTextYn', $(this).find("[id='changeTextYn']").val());
            }
        }
    });
    var approverCount = $("#userList li").length;

    //正文信息
    var sHtml =$('.summernote').summernote('code');
    formData.append('txtClobcn', sHtml);//正文html
    formData.append('txtTypeCd', '1');//正文类型 0-text 1-html 2-mhtml

    //审批id
    formData.append('appId', $('#appId').attr('value'));



	$.ajax({
		url : prefix + "/updateApproval",
		type : "post",
		data:formData,
		processData: false,  // 关键点
        contentType: false,  // 关键点
        success : function(r) {
            if (r.code == 0) {
                layer.alert(r.msg);
                window.opener.$("#dataTable").bootstrapTable('refresh');
                window.opener.$("#dataTable").find('[data-uniqueid='+$('#appId').attr('value')+']').find('.titleTable').click();
                forceClose();
            } else {
                alert(r.msg)
            }
        }
	});
}

function forceClose() {
    //解除绑定，一般放在提交触发事件中
    $(window).unbind('beforeunload');
	window.close();
}

function cancelEvent() {
    layer.confirm('The content is not saved.Are you sure you want to close it?',
        {
            title:'Cancel',
            closeBtn: 0,
            btn:['Yes','Cancel'],
            area: ['400px','160px'],
            yes: function(){
                $(window).unbind('beforeunload');
                window.close();
            },
            cancel: function(index) {
                layer.close(index);
            }
        }
    );
}

function showEmp(id){
	alert(id);
}

function edit(){
	
}

function reorder() {//重新排序

    var i = 0;
    var paraFirst;//第一个平行li
    var paraSeq;//平行的序号
    var meetPara = false;//遍历的是不是第一个平行li
    var liLenght = $('#userList li').length;

    $('#userList li').each(function () {
        if(i < liLenght){
            var paraAppClass = $(this).find('.para_appr').attr('class')
            var paraConClass = $(this).find('.para_con').attr('class')
            if(paraAppClass == 'para_appr active' || paraConClass == 'para_con active')
            {
                if(meetPara == false){
                    meetPara = true;
                    paraSeq = i;
                    i++;

                    if(paraAppClass == 'para_appr active'){
                        paraFirst = $(this)
                    }
                    else{
                        paraFirst = $(this)
                    }
                } else{
                    //console.log(paraFirst.nextAll().find('.para_appr.active,.para_con.active').parent('li');
                    paraFirst.after(paraFirst.nextAll().find('.para_appr.active,.para_con.active').parent('li'));
                }
                $(this).find("[id='seq']").text(paraSeq);
            }
            else
            {
                $(this).find("[id='seq']").text(i)
                i++;
            }
        }
    })
}

function cancelPara() {
    var paraAppCount= $('#userList').find('.para_appr.active').size();
    var paraConCount= $('#userList').find('.para_con.active').size();
    var totalPara = paraAppCount + paraConCount;
    if(totalPara > 0){
        var paraAppPickedCount= $('#userList .picked').find('.para_appr.active').size();
        var paraConPickedCount= $('#userList .picked').find('.para_con.active').size();
        var totalParaPicked = paraAppPickedCount + paraConPickedCount;

        if (totalPara <= (totalParaPicked+1)){//全部取消
            $('#userList').find('.activeHide').addClass('active');//取消平行时，根据为activeHide的，转化为原来的active。
            $('#userList').find('.type_button.active').show().siblings('button').show();
            $('#userList').find('.para_appr').removeClass('active').hide();
            $('#userList').find('.para_con').removeClass('active').hide();
        }
        else{//只取消选中的
            $('#userList .picked').find('.activeHide').addClass('active');//取消平行时，根据为activeHide的，转化为原来的active。
            $('#userList .picked').find('.type_button.active').show().siblings('button').show();
            $('#userList .picked').find('.para_appr').removeClass('active').hide();
            $('#userList .picked').find('.para_con').removeClass('active').hide();
        }
    }
}


//
function load(){
    $.ajax({
        method:'get',
        url: prefix + "/query/getApproval/"+$('#appId').val(),
        dataType: "json",
        success: function(data) {
            $('#titleInput').val(data.title);
            initFormData.append('apTtl', data.title);
            loadUserLine($('#appId').val());
            loadAttachment(data.attachmentList);
            loadContent(data.content);
        }
    });
}

function loadUserLine(appId){
    $.ajax({
        method:'get',
        url: prefix + "/query/listLines/",
        dataType: "json",
        data:{
            appId:appId
        },
        success: function(r) {
            $(".save_line_body").height(50);
            var modifyPath;
            var modifyText;

            $.each(r.list, function(index,line) {
                if (line.seq < $('#seq').val()){
                    //当前用户之前的审批人锁定，禁止编辑
                    $("#userList").append(
                        "<li class='singleApp block' data-edit='false'>" +
                        "<span id='seq' data-mail='" + line.receiverMail + "'>" + line.seq + "</span>" +
                        "<button id='appBtn' class='type_button activeHide' title='Approval' value ='1' >Appr</button>" +
                        "<button id='conBtn' class='type_button' title='Consent' value ='2'>Cons</button>" +
                        "<button id='notiBtn' class='type_button' title='Notification' value ='9'>Noti</button>" +
                        "<span id='postAppr' class='post_appr'  value ='3' style='display:none'>Post approval</span>" +
                        "<span id='paraAppr' class='para_appr'  value ='7' style='display:none'>Parallel approval</span>" +
                        "<span id='paraCon' class='para_con'  value ='4' style='display:none'>Parallel consent</span>" +
                        "<p>" + line.receiverName + '/' + line.receiverJob + "</p>" +
                        "<input type='hidden' id='empId' value='" + line.receiverEpid + "'/>" +
                        "<span id='operation' class='appOperation'><i class='fa fa-times'></i></span>" +
                        "<span id='arbDecision' class='appOperation' title='Arbitrary decision'><i class='fa fa-gavel'></i></span>" +
                        "<span id='editText' class='appOperation'title='Edit text'><i class='fa fa-pencil'></i></span>" +
                        "<span id='changeLine' class='appOperation' title='Change line'><i class='fa fa-user'></i></span>" +
                        "<input type='hidden' id='preReadTime' value='" + line.preReadTime + "'/>" +
                        "<input type='hidden' id='receiptTime' value='" + line.receiptTime + "'/>" +
                        "<input type='hidden' id='readTime' value='" + line.readTime + "'/>" +
                        "<input type='hidden' id='handleTime' value='" + line.handleTime + "'/>" +
                        "<input type='hidden' id='changeLineYn' value='" + line.changeLineYn + "'/>" +
                        "<input type='hidden' id='changeTextYn' value='" + line.changeTextYn + "'/>" +
                        "<input type='hidden' id='changeTextYn' value='" + line.changeTextYn + "'/>" +
                        "<input type='hidden' id='remark' value='" + line.remark + "'/>" +
                        "</li>"
                    );
                }else{
                    $("#userList").append(
                        "<li class='singleApp' data-edit='true'>" +
                        "<span id='seq' data-mail='" + line.receiverMail + "'>" + line.seq + "</span>" +
                        "<button id='appBtn' class='type_button activeHide' title='Approval' value ='1' >Appr</button>" +
                        "<button id='conBtn' class='type_button' title='Consent' value ='2'>Cons</button>" +
                        "<button id='notiBtn' class='type_button' title='Notification' value ='9'>Noti</button>" +
                        "<span id='postAppr' class='post_appr'  value ='3' style='display:none'>Post approval</span>" +
                        "<span id='paraAppr' class='para_appr'  value ='7' style='display:none'>Parallel approval</span>" +
                        "<span id='paraCon' class='para_con'  value ='4' style='display:none'>Parallel consent</span>" +
                        "<p>" + line.receiverName + '/' + line.receiverJob + "</p>" +
                        "<input type='hidden' id='empId' value='" + line.receiverEpid + "'/>" +
                        "<span id='operation' class='appOperation'><i class='fa fa-times'></i></span>" +
                        "<span id='arbDecision' class='appOperation' title='Arbitrary decision'><i class='fa fa-gavel'></i></span>" +
                        "<span id='editText' class='appOperation'title='Edit text'><i class='fa fa-pencil'></i></span>" +
                        "<span id='changeLine' class='appOperation' title='Change line'><i class='fa fa-user'></i></span>" +
                        "<input type='hidden' id='preReadTime' value='" + line.preReadTime + "'/>" +
                        "<input type='hidden' id='receiptTime' value='" + line.receiptTime + "'/>" +
                        "<input type='hidden' id='readTime' value='" + line.readTime + "'/>" +
                        "<input type='hidden' id='handleTime' value='" + line.handleTime + "'/>" +
                        "<input type='hidden' id='changeLineYn' value='" + line.changeLineYn + "'/>" +
                        "<input type='hidden' id='changeTextYn' value='" + line.changeTextYn + "'/>" +
                        "<input type='hidden' id='remark' value='" + line.remark + "'/>" +
                        "</li>"
                    );
                }


                switch (line.handleType) {
                    case 0:
                        $('#userList li').find('.type_button').remove();
                        $('#userList li').find('.appOperation').remove();
                        $("#userList li:last-child #seq").after("<button id='draftBtn' class='draftBtn active' value ='0'>Draft</button>");
                        break;
                    case 1:
                        $("#userList li:last-child button:nth-of-type(1)").addClass('active');
                        break;
                    case 2:
                        $('#userList li:last-child #appBtn').removeClass('activeHide');
                        $("#userList li:last-child button:nth-of-type(2)").addClass('active');
                        break;
                    case 9:
                        $('#userList li:last-child #appBtn').removeClass('activeHide');
                        $("#userList li:last-child button:nth-of-type(3)").addClass('active');
                        $('#userList li:last-child').find('.appOperation').not('#operation').addClass('clicked').hide();
                        break;
                    case 3:
                        $('#userList li:last-child .type_button').removeClass('activeHide').hide();
                        $("#userList li:last-child #postAppr").addClass('active').show();
                        break;
                    case 7:
                        $('#userList li:last-child .type_button').hide();
                        $("#userList li:last-child #paraAppr").addClass('active').show();
                        break;
                    case 4:
                        $('#userList li:last-child .type_button').hide();
                        $("#userList li:last-child #paraCon").addClass('active').show();
                        break;
                };

                if(line.arbPmtYn == 'N'){
                    $("#userList li:last-child #arbDecision").addClass('clicked');
                }
                if(line.txtMdfyPmtYn == 'N'){
                    $("#userList li:last-child #editText").addClass('clicked');
                }
                if(line.pathMdfyPmtYn == 'N'){
                    $("#userList li:last-child #changeLine").addClass('clicked');
                }

                if(line.receiverEpid == JSON.parse(sessionStorage.getItem("howAreYou")).userId){
                    modifyPath = line.pathMdfyPmtYn;
                    modifyText = line.txtMdfyPmtYn;
                }
            });

            if(modifyPath === 'N'){
                $(".save_search_body").block({
                    message: ''
                });
                $(".save_line_body").block({
                    message: ''
                });
            } else{
                $("#userList").find('.block').block({
                    message: ''
                });
            }

            if(modifyText === 'N'){
                $(".set_right_title").attr('disabled','true')
                $(".attchement_body").block({
                    message: ''
                });
                $(".app_file_body").block({
                    message: ''
                });
                $(".edit_body").block({
                    message: ''
                });
            }

            $(".save_line_body").height($(".save_line_body").height()+$("#userList li:last-child").outerHeight(true)*(r.list.length));
            wrapper.totalLines = r.list.length-1;
            initApproverCount= r.list.length;
        }
    });
}

function loadAttachment(data){
    var sumSize = 0;
    if($("#fileList li").length>0){
        $("#fileList").empty();
    }
    if(data != undefined && data.length >0){
        $.each( data, function( index, file ) {
            var type = file.fileType;
            var ico = '';
            if(type.indexOf('image')>-1){
                ico = "<span><i class='fa fa-file-image-o' style='color:#A03638' aria-hidden='true'></i></span>";
            }else if(type.indexOf('compressed')>-1){
                ico = "<span><i class='fa fa-file-archive-o' style='color:#F1B15A' aria-hidden='true'></i></span>";
            }else if(type.indexOf('word')>-1){
                ico = "<span><i class='fa fa-file-word-o' style='color:#2E5790' aria-hidden='true'></i></span>";
            }else if(type.indexOf('excel')>-1){
                ico = "<span><i class='fa fa-file-excel-o' style='color:#1E7145' aria-hidden='true'></i></span>";
            }else if(type.indexOf('sheet')>-1){
                ico = "<span><i class='fa fa-file-excel-o' style='color:#1E7145' aria-hidden='true'></i></span>";
            }else if(type.indexOf('text')>-1){
                ico = "<span><i class='fa fa-file-text-o' style='color:#C0C0C0' aria-hidden='true'></i></span>";
            }else if(type.indexOf('video')>-1){
                ico = "<span><i class='fa fa-file-video-o' style='color:#1E7145' aria-hidden='true'></i></span>";
            }else if(type.indexOf('presentation')>-1){
                ico = "<span><i class='fa fa-file-powerpoint-o' style='color:#8B008B' aria-hidden='true'></i></span>";
            }else if(type.indexOf('pdf')>-1){
                ico = "<span><i class='fa fa-file-pdf-o' style='color:#DC143C' aria-hidden='true'></i></span>";
            }else{
                ico = "<span><i class='fa fa-file' style='color:#0096D6' aria-hidden='true'></i></span>";
            }
            $("#fileList").append(
                "<li>" +
                "<span class='my-checkbox'><input class='check' id='"+file.fileName+"' type='checkbox' hidden><label for='"+file.fileName+"'></label></span>" +
                ico +
                "<span id='fileName'>"+file.fileOriginName+"</span>" +
                "<span id='fileSize' data-size='"+(file.fileSize/(1024*1024)).toFixed(2)+"'>("+(file.fileSize/1024).toFixed(2)+'KB'+")</span>" +
                "<input type='hidden' id='filePath' value='"+file.fileName+"'/>" +
                "<span id='operation'><i class='fa fa-times'></i></span>" +
                "</li>"
            );
            sumSize+=Number(file.fileSize/(1024*1024));
            var inputFile = new File([""], file.fileOriginName+'?'+file.fileSize, {type: file.fileType,lastModified: new Date() });
            attachment.set(file.fileOriginName,inputFile);
        });
        wrapper.totalFiles = data.length;
        wrapper.totalFileSize = Number(sumSize.toFixed(2));
        $(".app_file_body").height($(".app_file_body").height() + 18.4 * (data.length-1));
        $(".app_file_body").show();
    }else{
        $(".app_file_body").hide();
    }
}

function loadContent(code){
    $('.summernote').summernote({
        lang: 'zh-CN',
        placeholder: '请输入正文',
        minHeight: 320,
        dialogsFade: true, // Add fade effect on dialogs
        dialogsInBody: true, // Dialogs can be placed in body, not in summernote.
        disableDragAndDrop: false, // default false You can disable drag and drop
        toolbar: [
            ['style', ['bold', 'italic', 'underline', 'clear']],
            ['font', ['fontname','fontsize','color','forecolor','backcolor','strikethrough', 'superscript', 'subscript']],
            ['para', ['ul', 'ol', 'paragraph','height']],
            ['insert', ['table','picture','link']],
            ['misc', ['undo','redo','fullscreen', 'codeview', 'help']],
        ],
        callbacks: {
            onImageUpload: function (files, editor, $editable) {
                sendFile(files);
            }
        }
    });

    $('#content').summernote('code',code);

    initFormData.append('txtClobcn', $('.summernote').summernote('code'));
}

